# urllib imported for connections to URLs. 
# json imported for parsing data from ipwhois.app
import urllib
from urllib.request import urlopen
import json

# c2r stands for countries2regions. 2-part array used for matching with user locale. 
# Scalable for server distribution based on locale.
c2r = [
    ("US", "us-any-1"), ("PL", "eu-central-1"), ("DE", "eu-central-2"),
    ("BR", "sa-east-1"), ("IL", "us-midwest-1")
]

# User has the option to manually set IP address or use automatic detection. 
ip = input("Enter IP Address. Set to 0 for automatic detection: ")

# try-except statement used to let the user know of a possible error 
# (API availability or internet connectivity issues).
try:
    # Sending an API request to ipwhois.app
    response = urlopen("http://ipwhois.app/json/"+ip)
    ipgeolocation = json.load(response)
except:
    print('API is unavailable at this time (too many requests?) or failure to establish connection with ipwhois.app.')


# Country code and region output, field "country_code" and "region"
print (ipgeolocation["country_code"] , ipgeolocation["region"])


# x is a temporary variable used to connect the user's current location 
# (using country codes) to the nearest server.
# filter function used to eliminate redundant data.
x = list(filter(lambda x: x[0] == ipgeolocation["country_code"], c2r))
print(x)

# If ends up empty, print error message.
# If the country is outside the list after filteration, output a notification.
if not x:
    print("Country out of bounds and unsupported.")